# -*- encoding: utf-8 -*-
import sys, os
import cjson
import traceback

# add the directory of this very file to the pythonpath
mydir = os.path.dirname(__file__)
if mydir not in sys.path:
	sys.path += [mydir]
	
# add the location of the application to the pythonpath
import bootstrap_settings
if bootstrap_settings.APP_PATH not in sys.path:
	sys.path += [bootstrap_settings.APP_PATH]

import preamp.server.handler
from preamp.server.exceptions import BadRequestException

def application(environ, start_response):
	'''
	@param environ:
	@param start_response:  
	Called by the webserver.'''
	try:
		output = preamp.server.handler.handle(environ)
		http_status = {
			'error': '400 Bad Request',
			'ok': '200 OK'
			}[output['status']]
		content_type = 'application/json'
		output = cjson.encode(output)
	except: # show all exceptions on client-side
		output = traceback.format_exc()
		http_status = '500 Internal Server Error'
		content_type = 'text/plain'

	response_headers = [('Content-type', '%s; charset=UTF-8' % content_type),
						('Content-Length', str(len(output)))]
	start_response(http_status, response_headers)
	return output
